package view;

import java.awt.GridLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JLabel;
import javax.swing.JTextField;

import model.Perspective;
import controller.CommandManager;
import controller.TranslateCommand;
import controller.ZoomCommand;

@SuppressWarnings("serial")
public class ControlPanel extends BaseView
{
    // Constantes
    private final static int LAYOUT_LINES = 3;
    private final static int LAYOUT_COLUMNS = 2;

    // Attributs
    private JLabel lblZoom;
    private JLabel lblX;
    private JLabel lblY;
    private JTextField txtZoom;
    private JTextField txtX;
    private JTextField txtY;


    // Constructeur
    public ControlPanel(Perspective p) 
    {
    	perspective = p;
        this.setLayout(new GridLayout(LAYOUT_LINES, LAYOUT_COLUMNS));
    }


    private void addControls() 
    {
        this.add(lblZoom);
        this.add(txtZoom);
        this.add(lblX);
        this.add(txtX);
        this.add(lblY);
        this.add(txtY);
    }
    
    @Override
    protected void update(Perspective p) 
    {
        txtZoom.setText(p.getZoom() + "");
        txtX.setText(p.getX() + "");
        txtY.setText(p.getY() + "");
    }
    
    

    // Methodes publiques
	
	protected void init() {
        lblZoom = new JLabel("Zoom: ");
        lblX = new JLabel("X: ");
        lblY = new JLabel("Y: ");
        txtZoom = new JTextField();
        txtX = new JTextField();
        txtY = new JTextField();
        
        addControls();
        
		KeyListener translateListener = new KeyListener() {
			public void keyPressed(KeyEvent e) {
			}

			public void keyReleased(KeyEvent e) {
				try {
					int x = Integer.parseInt(txtX.getText());
					int y = Integer.parseInt(txtY.getText());
					TranslateCommand cmd = new TranslateCommand(perspective, x, y);
					CommandManager.getInstance().executeCommand(cmd);
				} catch (Exception ex) {
					//TODO: invalid number
					System.out.println(ex.getMessage());
				}
			}

			public void keyTyped(KeyEvent e) {
			}
		};

		KeyListener zoomListener = new KeyListener() {
			public void keyPressed(KeyEvent e) {
			}

			public void keyReleased(KeyEvent e) {
				try {
					float zoom = Float.parseFloat(txtZoom.getText());
					ZoomCommand cmd = new ZoomCommand(perspective, zoom);
					CommandManager.getInstance().executeCommand(cmd);
				} catch (Exception ex) {
					//TODO: invalid number
					System.out.println(ex.getMessage() + " | " + txtZoom.getText());
				}		
			}

			public void keyTyped(KeyEvent e) {		
			}
		};

		txtZoom.addKeyListener(zoomListener);
		txtX.addKeyListener(translateListener);
		txtY.addKeyListener(translateListener);
	}
}

